package com.blog.controller;

import com.blog.pojo.Admin;
import com.blog.pojo.Menu;
import com.blog.pojo.PageResult;
import com.blog.pojo.Roles;
import com.blog.service.AdminService;
import com.blog.service.MenuService;
import com.blog.service.RolesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: VE
 * @DATE: 2022/10/11 12:00
 * 描述:
 */
@RestController
@RequestMapping("menu")
public class MenuController {
    private Logger logger = LoggerFactory.getLogger(MenuController.class);
    @Autowired
    private MenuService menuService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RolesService rolesService;

    @GetMapping("test1")
    public String test1(){
        return "1111";
    }

    @GetMapping("initMenu")
    public PageResult initMenu(@CookieValue(value = "loginUser_id",required = false)Integer uid){
        logger.info("主菜单列表"+uid);
        //获取当前登录用户
        Admin loginAdmin =  adminService.load(uid);
        if(loginAdmin==null){
            return PageResult.none("没有登录");
        }
        //根据用户获取角色列表
        List<Roles> rolesList = rolesService.getRolesListByAdminId(loginAdmin.getAdminId());
        if(rolesList==null || rolesList.size()==0){
            return PageResult.none("未授权");
        }
        //根据角色获取一级权限列表
        Map<String,Object> pmap = new HashMap<>();
        pmap.put("rolesList",rolesList);
        List<Menu> menuList = menuService.getMenuByMap(pmap);
        Map<Integer,List<Menu>> menuListMap = new HashMap<>();
        //根据角色和一级菜单id获取二级菜单
        for(Menu menu:menuList){
            pmap.put("parentId",menu.getId());
            List<Menu> menus  = menuService.getMenuByMap(pmap);
            menuListMap.put(menu.getId(),menus);
        }
        //返回页面
        Map<String,Object> resultMap = new HashMap<>();
        //添加当前登录对象
        resultMap.put("admin",loginAdmin);
        //添加当前登录用户的角色列表
        resultMap.put("rolesList",rolesList);
        //添加当前登录用户的一级菜单
        resultMap.put("menuList",menuList);
        //添加当前登录用户的二级菜单
        resultMap.put("menuListMap",menuListMap);
        return PageResult.success("成功",resultMap);
    }
}
